# Avaliable environment:
#
# Download variable:Download variable
GIT_URL="https://gitee.com/anolis/ancert.git"
WEB_URL=("https://www.mersenne.org/download/software/v30/30.8/p95v308b17.linux64.tar.gz"
"https://cdn.pmylund.com/files/tools/cpuburn/linux/cpuburn-1.0-amd64.tar.gz"
"https://pyropus.ca./software/memtester/old-versions/memtester-4.6.0.tar.gz")
BM_NAME="ancert"
DEP_PKG_LIST="git make gcc gcc-c++ fio nvme-cli glx-utils python3 rpm-build bc lvm2 alsa-lib alsa-utils virt-what smartmontools hdparm OpenIPMI ipmitool freeipmi iperf3 sysstat stress-ng expect"

fetch()
{
    git_clone $GIT_URL $TONE_BM_CACHE_DIR/$BM_NAME
    cd $TONE_BM_CACHE_DIR
    wget_by_array
}

#extract_src()
#{
#    :
#}

build()
{
    local os_id="$(cat /etc/os-release|awk -F'"' '/^ID=/{print $(NF-1)}')"
    local dist_ver=$(rpm -E %{?dist}|sed -e 's/.an//g')

    test "${os_id}" = "anolis" || { echo "Error: Please build ancert kit in anolis os";exit 1; }
    # Support different Anolis OS versions
    if test "$dist_ver" -ge 23;then
        yum install -y xorg-x11-server-Xwayland x11perf xdpyinfo xvinfo xset python3-pyyaml clang
    else
        if test "$dist_ver" -ge 8;then
            yum install -y python3-pyyaml
        else
            yum repolist|grep -q epel || wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
            test "$dist_ver" -ge 7 && {  yum install -y python*-PyYAML || pip3 install pyyaml; } || \
            { echo "Error getting dist version($dist_ver),it should be greater than 7.x";exit 1; }
        fi
        yum install -y xorg-x11-utils xorg-x11-server-utils xorg-x11-apps clang
    fi

    # Source code installation
    fail_ins_msg=""
    for url in ${WEB_URL[*]};do
        pkg_name=$(basename $url)
        cd $TONE_BM_BUILD_DIR/${pkg_name%%.*} || { echo "Error: no such dir $TONE_BM_BUILD_DIR/${pkg_name%%.*}";exit 1; }
        if echo $pkg_name|grep -q cpuburn;then
            [ "$(arch)" = "x86_64" ] || continue
            command -v "cpuburn" &>/dev/null || /usr/bin/install -pv -D -m 0755 ./*/cpuburn /usr/bin/
        elif echo $pkg_name|grep -q p95v;then
            [ "$(arch)" = "x86_64" ] || continue
            command -v "mprime" &>/dev/null || /usr/bin/install -pv -D -m 0755 ./mprime /usr/bin/
        elif echo $pkg_name|grep -q memtester;then
            command -v "memtester" &>/dev/null || { cd memtester*;make && make install; }
        fi
        [ $? -ne 0 ] && fail_ins_msg="${fail_ins_msg}failed to install $pkg_name\n"
    done
    [ -n "$fail_ins_msg" ] && echo -e "$fail_ins_msg" && exit 1
}

install()
{
    [ -d "$TONE_BM_RUN_DIR/$BM_NAME" ] && rm -rf $TONE_BM_RUN_DIR/$BM_NAME
    cp -af $TONE_BM_CACHE_DIR/$BM_NAME $TONE_BM_RUN_DIR
}

uninstall()
{
    rm -rf $TONE_BM_RUN_DIR/$BM_NAME
    rm -rf $TONE_BM_CACHE_DIR
}